package com.apexsoft.assets.base.utils;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import com.apexsoft.assets.base.model.TreeModel;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 树形工具
 */

public class TreeUtil {

    /**
     *
     * @param dataList 数据
     * @param idCol ID字段名
     * @param fidCol 父级ID字段名
     * @return
     */
    public static List<TreeModel> buildTree(List<Map<String,Object>> dataList, String idCol, String fidCol){
        List<TreeModel> result = new ArrayList<>();
        for (Map<String,Object> map : dataList){
            String cid = MapUtil.getStr(map,idCol);
            String cfid = MapUtil.getStr(map,fidCol);
            result.add(new TreeModel(cid,cfid,map));
        }
        return result;
    }


    public static List<TreeModel> getChilds(List<TreeModel> list,String fid){
        List<TreeModel> result = new ArrayList<>();
        for (TreeModel model : list){
            if(model.IsChild(fid)) result.add(model);
        }
        return result;
    }

    public static Map<String, BigDecimal> add(List<TreeModel> list,String[] cols,String fid){
        Map<String, BigDecimal> result = new HashMap<>();
        for (TreeModel model : list){
            if(model.IsChild(fid)){
                Map<String,Object> map = model.getData();
                for (String col : cols){
                    Object obj = map.get(col);
                    BigDecimal number = result.getOrDefault(col,new BigDecimal(0));
                    if(obj instanceof String){
                        result.put(col,NumberUtil.add(number.toString(),(String) obj));
                    }else if(obj instanceof Number){
                        result.put(col,NumberUtil.add(number,(Number) obj));
                    }
                }
            }
        }
        return result;
    }

}
